package com.getan.boot.common.holder.security;

import com.getan.boot.common.holder.security.dto.UserDTO;
import com.getan.boot.common.utils.StringPool;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 上下文
 *
 * @author Bruce.Gong
 */
public class SecurityContextHolder {

    private static final String USER_KEY = "currentUser";
    private static final String TOKEN_KEY = "token";
    private static final String TENANT_KEY = "tenant";

    private static final ThreadLocal<Map<String, Object>> LOCAL = new InheritableThreadLocal<Map<String, Object>>() {
        @Override
        protected Map<String, Object> initialValue() {
            return new ConcurrentHashMap<>(4);
        }
    };

    /**
     * 设置当前登录用户
     *
     * @param user 用户信息
     */
    public static void setCurrentUser(UserDTO user) {
        LOCAL.get().put(USER_KEY, user);
    }

    /**
     * 设置Token
     *
     * @param token token
     */
    public static void setToken(String token) {
        LOCAL.get().put(TOKEN_KEY, token);
    }

    /**
     * 获取当前登录用户
     *
     * @return 当前登录用户
     */
    public static UserDTO getCurrentUser() {
        return (UserDTO) LOCAL.get().get(USER_KEY);
    }

    /**
     * 获取当前登录用户ID
     *
     * @return 登录用户ID
     */
    public static Long getCurrentUserId() {
        return Optional.ofNullable(getCurrentUser()).map(UserDTO::getUserId).orElse(-1L);
    }

    /**
     * 获取当前登录用户名
     *
     * @return 登录用户名
     */
    public static String getCurrentUserName() {
        return Optional.ofNullable(getCurrentUser()).map(UserDTO::getUsername).orElse(StringPool.EMPTY);
    }

    /**
     * 获取当前Token
     *
     * @return token
     */
    public static String getToken() {
        return (String) LOCAL.get().get(USER_KEY);
    }

}
